package jt.classic.app.dms.search;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jt.classic.system.ISystem;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.object.IObject;
import jt.classic.system.object.ObjectLCManager;
import jt.classic.system.purview.PurviewManager;
import jt.classic.system.user.IUser;
import jt.classic.system.user.UserManager;
import jt.classic.system.utils.AnnexTool;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.limp.basework.console.XSystemConfig;
import org.limp.mine.annex.AnnexInfo;


/**
 * 文档下载
 * @author mido
 *
 */
public class DmsDownloadAction extends DispatchAction {
    /**
     * 文档下载
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward download(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        AnnexInfo annexInfo = null;

        IObject obj = null;

        String id = request.getParameter("id");

        IUser user = UserManager.createGuestUser();

        try {
            SystemDataSource ds = SystemDataSource.getInstance();

            conn = ds.getConnection();

            ObjectLCManager olm = new ObjectLCManager(conn);

            obj = olm.getObjectById(id);

            if (obj != null) {
            	PurviewManager pm = new PurviewManager(conn);

                boolean purview = pm.purview4other(obj.id(), obj.ikey(), 4, user);

                if (purview) {
                    List contentList = (List) obj.icontent(obj.iobject()
                                                              .itable("DOC_BVFABRYJMQ"));

                    Map contentMap = (Map) contentList.get(0);

                    String pid = (String) contentMap.get("PK_DOC_BVFABRYJMQ");

                    AnnexTool tool = new AnnexTool(conn);

                    AnnexInfo[] annexs = tool.getAnnexs(pid, "DOC_BVFABRYJMQ");

                    if ((annexs != null) && (annexs.length > 0)) {
                        annexInfo = annexs[0];
                    }
                }else{
                	response.setContentType("text/html;charset=UTF-8");
                    response.getWriter().println("<script>");
                    response.getWriter().println("alert(\"您没有下载该文档的权限\");");
                    response.getWriter().println("</script>");
                    
                    
                    return null;
                }
            }
        } catch (Exception ex) {
            ISystem.catchException(this, ex);

            try {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("<script>");
                response.getWriter().println("alert(\"下载文档出现异常\");");
                response.getWriter().println("</script>");
                
                return null;
            } catch (IOException ex1) {
                ex1.printStackTrace(System.out);
            }
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        if (annexInfo != null) {
            String fileName = annexInfo.getTrueName();

            String repository = annexInfo.getRepository();

            String freehome = (String) XSystemConfig.config()
                                                    .getProperty(XSystemConfig.XSYSTEM_ANNEX_FREEHOME);

            String realpath = (String) XSystemConfig.config()
                                                    .getProperty(XSystemConfig.XSYSTEM_REALPATH);

            String restricthome = (String) XSystemConfig.config()
                                                        .getProperty(XSystemConfig.XSYSTEM_ANNEX_RESTRICTHOME);

            String home = "free".equals(annexInfo.getLocation()) ? freehome
                                                                 : (realpath +
                restricthome);

            try {
                File file = new File(new File(home, repository), fileName);

                BufferedInputStream input = new BufferedInputStream(new FileInputStream(
                            file));

                String head = "attachment; filename=" +
                    URLEncoder.encode(obj.iname(), "UTF-8");

                response.setHeader("Content-Disposition", head);
                response.setContentType("application/x-msdownload");
                response.setContentLength(input.available());

                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());

                int count = 0;
                byte[] b = new byte[8192];

                while ((count = input.read(b)) != -1) {
                    out.write(b, 0, count);
                }

                input.close();
                out.flush();
                out.close();
            } catch (FileNotFoundException ex) {
                try {
                    response.setContentType("text/html;charset=UTF-8");
                    response.getWriter().println("<script>");
                    response.getWriter().println("alert(\"您要下载的文档并不存在\");");
                    response.getWriter().println("</script>");
                } catch (IOException ex1) {
                    ex1.printStackTrace(System.out);
                }
            } catch (IOException ex) {
                //do nothing
            }
        }

        return null;
    }
}
